package com.zmwx.auth.application.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.zmwx.auth.application.context.LoginContextHolder;
import com.zmwx.auth.application.convert.AuthUserDTOToConverter;
import com.zmwx.auth.entity.AuthUserDTO;
import com.zmwx.auth.application.enums.AuthUserStateEnum;
import com.zmwx.auth.common.entity.Result;
import com.zmwx.auth.domain.entityDO.AuthUserBO;
import com.zmwx.auth.domain.service.AuthUserDomainService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private AuthUserDomainService authUserDomainService;

    /**
     * 用户注册
     *
     * @return
     */
    @RequestMapping("/register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        try {
            checkUserInfo(authUserDTO);
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()), "邮箱不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()), "密码不能为空");
            AuthUserBO authUserBO = AuthUserDTOToConverter.INSTANCE.convertDTOToBo(authUserDTO);
            authUserBO.setStatus(AuthUserStateEnum.CLOSE.getCode());
            Boolean register = authUserDomainService.register(authUserBO);
            if (register) {
                return Result.ok("注册成功");
            } else {
                return Result.fail("注册失败");
            }

        } catch (Exception e) {
            log.error("注册失败", e.getMessage(), e);
            return Result.fail("注册失败");
        }
    }

    /**
     * 修改用户信息
     *
     * @return
     */
    @RequestMapping("/update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        try {
            checkUserInfo(authUserDTO);
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
            AuthUserBO authUserBO = AuthUserDTOToConverter.INSTANCE.convertDTOToBo(authUserDTO);
            Boolean register = authUserDomainService.update(authUserBO);
            if (register) {
                return Result.ok("更新成功");
            } else {
                return Result.fail("更新用户信息失败可能是未找到UserName");
            }
        } catch (Exception e) {
            log.error("更新用户信息失败", e.getMessage(), e);

            return Result.fail("更新用户信息失败");
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @RequestMapping("/getUserInfo")
    public Result<AuthUserDTO> getUserInfo() {
        try {
            String loginId =(String) LoginContextHolder.get("loginId");

            AuthUserDTO authUserDTO=new AuthUserDTO();
            authUserDTO.setUserName(loginId);
            if (log.isInfoEnabled()) {
                log.info("获取用户信息:{}", JSON.toJSONString(authUserDTO));
            }
            checkUserInfo(authUserDTO);
            // 修改成从线程变量里面拿用户名

            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
            AuthUserBO authUserBO = AuthUserDTOToConverter.INSTANCE.convertDTOToBo(authUserDTO);
            AuthUserDTO resultDTO =AuthUserDTOToConverter.INSTANCE.convertBOToDTO(authUserDomainService.getUserInfo(authUserBO));
            return Result.ok(resultDTO);
            //  return Result.fail("更新用户信息失败可能是未找到UserName");
        } catch (Exception e) {
            log.error("获取用户信息失败", e.getMessage(), e);
            return Result.fail("获取用户信息失败");
        }
    }

    /**
     * 注销用户 删除
     *
     * @return
     */
    @RequestMapping("/deleteUser")
    public Result<Boolean> deleteUser(@RequestBody AuthUserDTO authUserDTO) {
        try {
            checkUserInfo(authUserDTO);
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "userName不能为空");
            // Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()), "密码不能为空");
            AuthUserBO authUserBO = AuthUserDTOToConverter.INSTANCE.convertDTOToBo(authUserDTO);
            authUserBO.setStatus(AuthUserStateEnum.CLOSE.getCode());
            Boolean register = authUserDomainService.delete(authUserBO);
            if (register) {
                return Result.ok("删除成功成功");
            } else {
                return Result.fail("删除失败");
            }

        } catch (Exception e) {
            log.error("注册失败", e.getMessage(), e);
            return Result.fail("删除失败");
        }
    }

    /**
     * 用户启用/禁用
     */
    @RequestMapping("/changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getStatus(), "用户状态不能为空");
            AuthUserBO authUserBO = AuthUserDTOToConverter.INSTANCE.INSTANCE.convertDTOToBo(authUserDTO);
            return Result.ok(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.changeStatus.error:{}", e.getMessage(), e);
            return Result.fail("启用/禁用用户信息失败");
        }
    }

    private void checkUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
    }


    @RequestMapping("/doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode) {
        try {
            System.out.println(validCode);
            log.info("UserController.doLogin.validCode:{}", validCode);
            Preconditions.checkArgument(!StringUtils.isBlank(validCode), "验证码不能为空");
            SaTokenInfo tokenInfo = authUserDomainService.doLogin(validCode);
            return Result.ok(tokenInfo);
        } catch (Exception e) {
            log.error("UserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }

    }

    @RequestMapping("/logOut")
    public Result<SaTokenInfo> logout(@RequestParam("userName") String userName) {
        try {

            log.info("UserController.logOut.validCode:{}", userName);
            Preconditions.checkArgument(!StringUtils.isBlank(userName), "用户名不能为空");
            StpUtil.logout(userName);

            return Result.ok();
        } catch (Exception e) {
            log.error("UserController.logOut.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }

    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("/isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

}